package com.cloud.salon.client.authority.service.impl;

import com.cloud.salon.client.authority.repository.UserRoleRepository;
import com.cloud.salon.client.authority.service.RoleService;
import com.cloud.salon.client.authority.service.UserRoleService;
import com.cloud.salon.client.authority.service.UserService;
import com.cloud.salon.common.base.entity.authority.Role;
import com.cloud.salon.common.base.entity.authority.User;
import com.cloud.salon.common.base.entity.authority.relation.UserRole;
import com.cloud.salon.common.base.response.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author wolf--LZH
 * @CreateDate 2019/5/3 0003 下午 3:47
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    public Res setUserRoles(Integer userId, List<Integer> roleIdList) {
        // 获取要设置的用户实体, 若为空则返回错误信息
        Res<User> userRes = userService.findById(userId);
        if(userRes.getData() == null)
            return new Res(-3, "无此用户");

        // 获取当前用户所具备的角色
        Res<List<Role>> userRolesRes = roleService.findByUser(userId);
        List<Role> userRoleList = userRolesRes.getData();

        // 通过id列表获取要设置的角色列表
        Res<List<Role>> rolesRes = roleService.findByIdList(roleIdList);
        List<Role> roleList = null;
        if(rolesRes.getData() == null)
            return new Res(-3, "获取要设置的角色列表失败,请确保参数正确");
        else
            roleList = rolesRes.getData();

        // 添加当前用户不具备的角色
        for (Role role: roleList) {
            if(!userRoleList.contains(role)) {
                // 新增实体
                UserRole save = new UserRole();
                save.setUserId(userId);
                save.setRoleId(role.getId());

                userRoleRepository.save(save);
            }
        }

        // 删除不在具备的角色
        for (Role role: userRoleList) {
            if(!roleList.contains(role)) {
                // 删除该角色
                userRoleRepository.deleteByUserIdAndRoleId(userId, role.getId());
            }
        }

        return new Res(0, "操作成功");
    }
}
